<template>
  <div>
    <n-card title="我的活动">
      <template #header-extra>
        <n-space>
          <n-badge :value="pendingReviewCount" :show="pendingReviewCount > 0" type="warning">
            <n-button size="small" @click="loadMyActivities">
              <template #icon>
                <n-icon><RefreshOutline /></n-icon>
              </template>
              刷新
            </n-button>
          </n-badge>
        </n-space>
      </template>
      
      <n-tabs type="line" animated>
        <n-tab-pane name="all" tab="全部">
          <n-list hoverable v-if="allActivities.length">
            <n-list-item v-for="activity in allActivities" :key="activity.id">
              <n-thing>
                <template #header>
                  {{ activity.title }}
                </template>
                <template #description>
                  <n-space size="small">
                    <n-text depth="3">{{ formatDate(activity.startTime) }}</n-text>
                    <n-tag v-if="getEnrollmentStatus(activity.id)" size="small" :type="getStatusType(getEnrollmentStatus(activity.id))">
                      {{ getStatusText(getEnrollmentStatus(activity.id)) }}
                    </n-tag>
                    <n-tag v-if="hasCheckedIn(activity.id)" size="small" type="success">
                      已签到
                    </n-tag>
                    <n-tag v-if="hasCheckedOut(activity.id)" size="small" type="success">
                      已签退
                    </n-tag>
                  </n-space>
                </template>
                {{ activity.description?.substring(0, 100) }}...
                <template #action>
                  <n-space>
                    <n-button size="small" @click="router.push(`/activity/detail/${activity.id}`)">
                      查看详情
                    </n-button>
                    <!-- 签到按钮 -->
                    <n-button 
                      v-if="canCheckIn(activity)" 
                      size="small" 
                      type="primary"
                      @click="handleCheckIn(activity.id)"
                    >
                      <template #icon>
                        <n-icon><CheckmarkCircleOutline /></n-icon>
                      </template>
                      签到
                    </n-button>
                    <!-- 签退按钮 -->
                    <n-button 
                      v-if="canCheckOut(activity.id)" 
                      size="small" 
                      type="success"
                      @click="handleCheckOut(activity.id)"
                    >
                      <template #icon>
                        <n-icon><LogOutOutline /></n-icon>
                      </template>
                      签退
                    </n-button>
                    <!-- 取消按钮 -->
                    <n-popconfirm
                      v-if="canCancel(activity)"
                      @positive-click="() => showCancelModal(activity.id)"
                    >
                      <template #trigger>
                        <n-button size="small" type="warning">
                          取消报名
                        </n-button>
                      </template>
                      确定要取消报名吗？取消后可能会扣除积分。
                    </n-popconfirm>
                  </n-space>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
          <n-empty v-else description="暂无活动" />
        </n-tab-pane>

        <n-tab-pane name="enrolled" tab="已报名">
          <n-list hoverable v-if="enrolledActivities.length">
            <n-list-item v-for="activity in enrolledActivities" :key="activity.id">
              <n-thing>
                <template #header>
                  {{ activity.title }}
                </template>
                <template #description>
                  <n-space size="small">
                    <n-text depth="3">{{ formatDate(activity.startTime) }}</n-text>
                    <n-tag size="small" :type="getStatusType(getEnrollmentStatus(activity.id))">
                      {{ getStatusText(getEnrollmentStatus(activity.id)) }}
                    </n-tag>
                    <n-tag v-if="hasCheckedIn(activity.id)" size="small" type="success">
                      已签到
                    </n-tag>
                  </n-space>
                </template>
                {{ activity.description?.substring(0, 100) }}...
                <template #action>
                  <n-space>
                    <n-button size="small" @click="router.push(`/activity/detail/${activity.id}`)">
                      查看详情
                    </n-button>
                    <!-- 签到按钮 -->
                    <n-button 
                      v-if="canCheckIn(activity)" 
                      size="small" 
                      type="primary"
                      @click="handleCheckIn(activity.id)"
                    >
                      <template #icon>
                        <n-icon><CheckmarkCircleOutline /></n-icon>
                      </template>
                      签到
                    </n-button>
                    <!-- 签退按钮 -->
                    <n-button 
                      v-if="canCheckOut(activity.id)" 
                      size="small" 
                      type="success"
                      @click="handleCheckOut(activity.id)"
                    >
                      <template #icon>
                        <n-icon><LogOutOutline /></n-icon>
                      </template>
                      签退
                    </n-button>
                    <!-- 取消按钮 -->
                    <n-popconfirm
                      v-if="canCancel(activity)"
                      @positive-click="() => showCancelModal(activity.id)"
                    >
                      <template #trigger>
                        <n-button size="small" type="warning">
                          取消报名
                        </n-button>
                      </template>
                      确定要取消报名吗？取消后可能会扣除积分。
                    </n-popconfirm>
                  </n-space>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
          <n-empty v-else description="暂无活动" />
        </n-tab-pane>

        <n-tab-pane name="completed" tab="已完成">
          <n-list hoverable v-if="completedActivities.length">
            <n-list-item v-for="activity in completedActivities" :key="activity.id">
              <n-thing>
                <template #header>
                  {{ activity.title }}
                </template>
                <template #description>
                  <n-space size="small">
                    <n-text depth="3">{{ formatDate(activity.startTime) }}</n-text>
                    <n-tag size="small" type="success">已完成</n-tag>
                    <n-tag v-if="getServiceHours(activity.id)" size="small" type="info">
                      服务时长: {{ getServiceHours(activity.id) }} 小时
                    </n-tag>
                  </n-space>
                </template>
                {{ activity.description?.substring(0, 100) }}...
                <template #action>
                  <n-button size="small" @click="router.push(`/activity/detail/${activity.id}`)">
                    查看详情
                  </n-button>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
          <n-empty v-else description="暂无活动" />
        </n-tab-pane>
      </n-tabs>
    </n-card>

    <!-- 取消报名对话框 -->
    <n-modal v-model:show="showCancelDialog" preset="dialog" title="取消报名">
      <n-space vertical>
        <n-text>请填写取消原因：</n-text>
        <n-input
          v-model:value="cancelReason"
          type="textarea"
          placeholder="请输入取消原因..."
          :rows="4"
        />
        <n-text depth="3" type="warning">
          ⚠️ 温馨提示：
          <br>• 活动开始前取消：扣除 5 分
          <br>• 活动开始后取消：扣除 15 分
          <br>• 30天内取消3次以上：加倍扣分并限制报名30天
        </n-text>
      </n-space>
      <template #action>
        <n-space>
          <n-button @click="showCancelDialog = false">取消</n-button>
          <n-button type="warning" @click="confirmCancel">确认取消</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserEnrollments, getActivityDetail, checkIn, checkOut, cancelEnrollment } from '@/api/activity'
import { RefreshOutline, CheckmarkCircleOutline, LogOutOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()

const enrollments = ref([])
const activities = ref([])
const showCancelDialog = ref(false)
const cancelReason = ref('')
const currentCancelActivityId = ref(null)

const allActivities = computed(() => activities.value)
const enrolledActivities = computed(() => {
  return activities.value.filter((activity) => {
    const enrollment = enrollments.value.find(e => e.activityId === activity.id)
    return enrollment && ['ENROLLED', 'APPROVED'].includes(enrollment.status)
  })
})
const completedActivities = computed(() => {
  return activities.value.filter((activity) => {
    const enrollment = enrollments.value.find(e => e.activityId === activity.id)
    return enrollment && enrollment.status === 'COMPLETED'
  })
})

// 待审核数量（ENROLLED状态表示待管理员审核）
const pendingReviewCount = computed(() => {
  return enrollments.value.filter(e => e.status === 'ENROLLED').length
})

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

const getEnrollmentStatus = (activityId) => {
  const enrollment = enrollments.value.find(e => e.activityId === activityId)
  return enrollment?.status || ''
}

const getEnrollment = (activityId) => {
  return enrollments.value.find(e => e.activityId === activityId)
}

const hasCheckedIn = (activityId) => {
  const enrollment = getEnrollment(activityId)
  return enrollment?.checkInTime != null
}

const hasCheckedOut = (activityId) => {
  const enrollment = getEnrollment(activityId)
  return enrollment?.checkOutTime != null
}

const getServiceHours = (activityId) => {
  const activity = activities.value.find(a => a.id === activityId)
  const enrollment = getEnrollment(activityId)
  
  // 如果已签到，使用活动设置的时长
  if (enrollment?.checkInTime && activity?.startTime && activity?.endTime) {
    const startTime = new Date(activity.startTime)
    const endTime = new Date(activity.endTime)
    const hours = Math.abs(endTime - startTime) / (1000 * 60 * 60)
    return hours.toFixed(1)
  }
  
  return null
}

// 判断是否可以签到
const canCheckIn = (activity) => {
  const enrollment = getEnrollment(activity.id)
  if (!enrollment) return false
  
  // 必须是已通过或已报名状态
  if (!['APPROVED', 'ENROLLED'].includes(enrollment.status)) return false
  
  // 未签到
  if (enrollment.checkInTime) return false
  
  // 活动必须是进行中
  if (activity.status !== 'IN_PROGRESS' && activity.status !== 'RECRUITING') return true
  
  return true
}

// 判断是否可以签退
const canCheckOut = (activityId) => {
  const enrollment = getEnrollment(activityId)
  if (!enrollment) return false
  
  // 必须已签到
  if (!enrollment.checkInTime) return false
  
  // 未签退
  if (enrollment.checkOutTime) return false
  
  return true
}

// 判断是否可以取消
const canCancel = (activity) => {
  const enrollment = getEnrollment(activity.id)
  if (!enrollment) return false
  
  // 只有已报名或已通过状态可以取消
  if (!['ENROLLED', 'APPROVED'].includes(enrollment.status)) return false
  
  // 活动未完成
  if (activity.status === 'COMPLETED') return false
  
  return true
}

const getStatusType = (status) => {
  const typeMap = {
    'ENROLLED': 'info',
    'APPROVED': 'success',
    'REJECTED': 'error',
    'COMPLETED': 'success',
    'CANCELLED': 'warning'
  }
  return typeMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    'ENROLLED': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || status
}

// 签到
const handleCheckIn = async (activityId) => {
  try {
    await checkIn(activityId, { userId: userStore.userId })
    window.$message?.success('签到成功')
    await loadMyActivities()
  } catch (error) {
    console.error('签到失败:', error)
    window.$message?.error(error.response?.data?.message || '签到失败')
  }
}

// 签退
const handleCheckOut = async (activityId) => {
  try {
    await checkOut(activityId, { userId: userStore.userId })
    window.$message?.success('签退成功，服务时长已记录')
    await loadMyActivities()
  } catch (error) {
    console.error('签退失败:', error)
    window.$message?.error(error.response?.data?.message || '签退失败')
  }
}

// 显示取消对话框
const showCancelModal = (activityId) => {
  currentCancelActivityId.value = activityId
  cancelReason.value = ''
  showCancelDialog.value = true
}

// 确认取消
const confirmCancel = async () => {
  if (!cancelReason.value.trim()) {
    window.$message?.warning('请填写取消原因')
    return
  }

  try {
    await cancelEnrollment(currentCancelActivityId.value, {
      userId: userStore.userId,
      cancelReason: cancelReason.value
    })
    window.$message?.success('已取消报名')
    showCancelDialog.value = false
    await loadMyActivities()
  } catch (error) {
    console.error('取消报名失败:', error)
    window.$message?.error(error.response?.data?.message || '取消报名失败')
  }
}

const loadMyActivities = async () => {
  try {
    const res = await getUserEnrollments(userStore.userId)
    const newEnrollments = res.data || []
    
    // 检查是否有新的审核结果
    if (enrollments.value.length > 0) {
      const newApproved = newEnrollments.filter(e => 
        e.status === 'APPROVED' && 
        enrollments.value.find(old => old.id === e.id)?.status !== 'APPROVED'
      ).length
      
      const newRejected = newEnrollments.filter(e => 
        e.status === 'REJECTED' && 
        enrollments.value.find(old => old.id === e.id)?.status !== 'REJECTED'
      ).length
      
      if (newApproved > 0) {
        window.$notification?.success({
          title: '审核通过',
          content: `您有 ${newApproved} 个活动报名已通过审核！`,
          duration: 5000
        })
      }
      
      if (newRejected > 0) {
        window.$notification?.warning({
          title: '审核未通过',
          content: `您有 ${newRejected} 个活动报名未通过审核`,
          duration: 5000
        })
      }
    }
    
    enrollments.value = newEnrollments
    
    if (enrollments.value.length === 0) {
      activities.value = []
      return
    }
    
    // 加载活动详情
    const activityPromises = enrollments.value.map(e => getActivityDetail(e.activityId))
    const activityResults = await Promise.all(activityPromises)
    activities.value = activityResults.map(r => r.data).filter(a => a != null)
  } catch (error) {
    console.error('加载我的活动失败:', error)
    window.$message?.error('加载活动失败')
  }
}

onMounted(() => {
  loadMyActivities()
})
</script>
